package framework.jackson;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

import java.io.IOException;

/**
 * 嵌套对象 的属性平铺开来
 *
     {
         "name": "John",
         "contact": {
             "email": "john@example.com",
             "address": {
                 "street": "123 Main St",
                 "city": "San Francisco",
                 "state": "CA"
             }
         }
     }
 *
 */
public class TestNestedObj {

    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        String json = "{\"name\":\"John\",\"contact\":{\"email\":\"john@example.com\",\"address\":{\"street\":\"123-Main St\",\"city\":\"San Francisco\",\"state\":\"CA\"}}}";
        Person person = mapper.readValue(json, Person.class);

        String str = mapper.writeValueAsString(person);
        System.out.println(str);
    }

    @Data
    public static class Person {
        private String name;

        @JsonIgnore
        // @JsonProperty("contact_email")
        private String contactEmail;

        @JsonIgnore
        // @JsonProperty("contact_address_street")
        private String contactAddressStreet;

        @JsonIgnore
        // @JsonProperty("contact_address_city")
        private String contactAddressCity;

        @JsonIgnore
        // @JsonProperty("contact_address_state")
        private String contactAddressState;

        public void setContact(ContactInfo contact) {
            this.contactEmail = contact.getEmail();
            this.contactAddressStreet = contact.getAddress().getStreet();
            this.contactAddressCity = contact.getAddress().getCity();
            this.contactAddressState = contact.getAddress().getState();
        }

        public ContactInfo getContact() {
            ContactInfo contactInfo = new ContactInfo();
            contactInfo.setEmail(this.contactEmail);

            Address address = new Address();
            address.setStreet(this.contactAddressStreet);
            address.setCity(this.contactAddressCity);
            address.setState(this.contactAddressState);

            contactInfo.setAddress(address);
            return contactInfo;
        }
    }

    @Data
    public static class ContactInfo {
        private String email;
        private Address address;
    }

    @Data
    public static class Address {
        private String street;
        private String city;
        private String state;
    }
}
